<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>websocket</title>
 
<script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js" ></script>
<script type="text/javascript">
var ws = null;
var userId = null

function WebSocketTest()
{
   if ("WebSocket" in window)
   {
      userId = $("input[name=userId]").val();
      if(!userId){
    	  alert("请输入账号！");
      }
      // 打开一个 web socket
      var url = "ws://" + getHostAndProjectName() +"/"+ userId;
      console.info(url);
      ws = new WebSocket(url);
       
      ws.onopen = function()
      {
         // Web Socket 已连接上，使用 send() 方法发送数据
         ws.send("{'formUserId':'"+userId+"','content':'hello websocket','createTime':'"+new Date()+"'}");
      };
       
      ws.onmessage = function (evt) 
      { 
         var received_msg = evt.data;
         console.info(received_msg);
      };
       
      ws.onclose = function()
      { 
         // 关闭 websocket
         alert("连接已关闭..."); 
      };
   }
   
   else
   {
      // 浏览器不支持 WebSocket
      alert("您的浏览器不支持 WebSocket!");
   }
}

function getHostAndProjectName(){
	var host = window.location.host;
	var pathName = window.location.pathname;
	var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
	return host + projectName;
}

function sendMsg(){
	if(!ws){
		alert("请先连接服务器！");
		return;
	}
	var content = $("input[name=content]").val();
	if(!content){
		alert("请输入要发送的内容！");
		return;
	}
	// Web Socket 已连接上，使用 send() 方法发送数据
    ws.send("{'formUserId':'"+userId+"','content':'"+content+"','createTime':'"+new Date()+"'}");
    $("input[name=content]").val("");
}
</script>
</head>
<body>
<h2>Hello World!</h2>
<div>
	<input type="text" name="userId"/> <button onclick="WebSocketTest()">连接</button>
</div>
<div>
	<input type="text" name="content"/> <button onclick="sendMsg()">发送消息</button>
</div>
</body>
</html>
